using System;
using System.IO;
using System.Xml.Serialization;
using LetsDoIt.Common;

namespace LetsDoIt
{
    /// <summary>
    /// factory class used for application settings
    /// </summary>
	public class SettingsFactory
	{
        /// <summary>
        /// Load application settings
        /// </summary>
        /// <returns>application Settings object</returns>
		public static Settings LoadSettings()
		{
			Settings result = null;
			string filePath = Path.Combine(Utils.Utils.ApplicationPath(), FileSystemNames.SETTINGS_FILE_NAME);
			if (File.Exists(filePath))
			{
				using (FileStream fs = File.OpenRead(filePath))
				{
					XmlSerializer ser = new XmlSerializer(typeof (Settings));
					result = ser.Deserialize(fs) as Settings;
                    if (!string.IsNullOrEmpty(result.Password))
				        result.Password = Utils.DESCrypt.Decrypt(result.Password);
				}
			}
			return result;
		}

        /// <summary>
        /// Save application settings
        /// </summary>
        /// <param name="settings">input application Settings</param>
		public static void SaveSettings(Settings settings)
		{
			string filePath = Path.Combine(Utils.Utils.ApplicationPath(), FileSystemNames.SETTINGS_FILE_NAME);
			if (File.Exists(filePath))
				File.Delete(filePath);
			using (FileStream fs = File.Create(filePath))
			{
                //clone settings to encrypt password
			    Settings toSave = settings.Clone() as Settings;
                if (!string.IsNullOrEmpty(toSave.Password))
			        toSave.Password = Utils.DESCrypt.Encrypt(toSave.Password);

				XmlSerializer ser = new XmlSerializer(typeof(Settings));
                ser.Serialize(fs, toSave);
			}
		}

        
	}
}